# coding = UTF-8
# 获取xy手柄的方向 通过pygame控制小方块
# 通道0: x轴
# 通道1: y轴
# 通道2: 按键

import smbus
import time
import pygame
import sys
from my_class import TheRect

pygame.init()
winx = 300
winy = 300
screen = pygame.display.set_mode((winx,winy))
rect = TheRect(100,100,10,10,(62, 148, 214))
speedx = 2
speedy =2

bus = smbus.SMBus(1)
addr = 0x48
# 获取初始状态的值
# bus.write_byte(addr,0)
# x0 = bus.read_byte(addr)
x0 = 192
y0 = 192
range = 10 # 可接受的误差幅度
# bus.write_byte(addr,1)
# y0 = bus.read_byte(addr)
# print(f'x0:{x0}, y0:{y0}')
last_press_num = None

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # 0b00000000  通道0, x
    # 0b00000001  通道1, y
    # 0b00000010  通道2, button
    # 0b00000011  通道3,
    # 写入控制字 control byte
    # bus.write_byte(addr,0b00000010)
    # bus.write_byte(addr,0x01)
    ain = ['x','y','press']
    is_moving_x = False
    is_moving_y = False
    i = 0 # x
    bus.write_byte(addr,0)
    # 读取采样数据
    read_res = bus.read_byte(addr)
    if read_res<x0-range:
        is_moving_x = True
        rect.move(-speedx,0)
        print('left')
    if read_res>x0+range:
        is_moving_x = True
        rect.move(speedx,0)
        print('right')
    if x0-range<read_res<x0+range:
        is_moving_y = False
    # print(ain[0],read_res)

    i = 1 # y
    bus.write_byte(addr,1)
    # 读取采样数据
    read_res = bus.read_byte(addr)
    if read_res<y0-range:
        is_moving_y = True
        rect.move(0,-speedy)
        print('up')
    if read_res>y0+range:
        is_moving_y = True
        rect.move(0,speedy)
        print('down')
    if y0-range<read_res<y0+range:
        is_moving_y = False
    # print(ain[1],read_res)
    bus.write_byte(addr,2)
    current_press_num = bus.read_byte(addr)
    if current_press_num == last_press_num == 0:
        speedx +=1
        speedy +=1
        print('pressed')
    last_press_num = current_press_num
    # print(ain[2],current_press_num)

    if not is_moving_x and not is_moving_y:
        print('still')
    pygame.display.update()
    screen.fill((0,0,0))
    rect.draw(screen)
    time.sleep(0.5)